import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  lang: 0,
  cartFoods: [],
  isTakeaway: true
}
const getters = {
  // 取出语言类型
  takelanguager (state) {
    return state.lang
  },
  //  总价格
  totalPrice (state) {
    let total = 0
    state.cartFoods.filter(({ num }) => num !== 0).forEach(({ cost, num }) => {
      total += cost * num
    })
    return total.toFixed(2)
  },
  //  总数量
  totalCount (state) {
    let allNum = 0
    state.cartFoods.filter(({ num }) => num !== 0).forEach(({ num }) => {
      allNum += num
    })
    return allNum
  },
}
const mutations = {
  // 存入语言类型
  depositlanguager (state, kind) {
    state.lang = kind
  },
  ADD_CART (state, { food, options, price }) {
    let foundFood = options ?
      state.cartFoods.find(({ specials, id }) => id === food.id && specials && specials.toString() === options.toString())
      : state.cartFoods.find(({ id }) => id === food.id)
    if (!foundFood) {
      food.num = 1
      if (options) {
        food.specials = options
        food.cost = price || food.cost
      }
      state.cartFoods = [food, ...state.cartFoods]
    } else {
      foundFood.num += 1
    }
  },
  DEC_CART (state, food) {
    let index = food.specials ?
      state.cartFoods.findIndex(({ specials, id }) => id === food.id && specials && specials.toString() === food.specials.toString())
      : state.cartFoods.findIndex(({ id }) => id === food.id)
    if (state.cartFoods[index].num === 1) {
      state.cartFoods.splice(index, 1)
    } else {
      state.cartFoods[index].num -= 1
    }
  },
  EMPTY (state) {
    state.cartFoods = []
  },
  CHANGE_TYPE (state) {
    state.isTakeaway = !state.isTakeaway
  }
}


export default new Vuex.Store({
  state,
  getters,
  mutations
})
